<?php

namespace addons\litestore\model;

use app\common\library\Ems as Emslib;
use think\Config;
use think\Model;
use think\Db;
use app\common\controller\Fedex;
use app\common\controller\Usps;
use app\admin\model\litestore\Litestoreorder as LitestoreorderModel;

class Litestoreorder extends Model
{
    // 表名
    protected $name = 'litestore_order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    // 追加属性
    protected $append = [
        'pay_status_text',
        'pay_time_text',
        'freight_status_text',
        'freight_time_text',
        'receipt_status_text',
        'receipt_time_text',
        'order_status_text',
        'creattime_text',
    ];

    public function cancel($user_id,$order_id){
        if ($this['pay_status'] === '20') {
            $this->error = '已付款订单不可取消';
            return false;
        }
        $goods = $this['goods'];
        $this->backGoodsStock($goods);

        $order = self::get([
            'order_id' => $order_id,
            'litestoreorder.user_id' => $user_id,
            'order_status' => ['<>', '20']
        ],['address']);

        //邮件通知
        $email = $order['address']['email_address'];
        $msg = 'Your order: '.$order['order_no'].', cancelled！';
        $ret = Emslib::notice($email, $msg);

        return $order->save([
            'order_status' => '20'
        ]);
    }
    private function backGoodsStock(&$goodsList)
    {
        $goodsSpecSave = [];
        foreach ($goodsList as $goods) {
            // 下单减库存
            if ($goods['deduct_stock_type'] === '10') {
                $goodsSpecSave[] = [
                    'goods_spec_id' => $goods['goods_spec_id'],
                    'stock_num' => ['inc', $goods['total_num']]
                ];
            }
        }
        if(!empty($goodsSpecSave)){
        // 更新商品规格库存
            return (new Litestoregoodsspec)->isUpdate()->saveAll($goodsSpecSave);
        }
        return true;
    }

    public function finish($user_id,$order_id){
        if (!$order = self::get([
            'order_id' => $order_id,
            'litestoreorder.user_id' => $user_id,
            'order_status' => ['<>', '20']
        ],['goods','address'])) {
            throw new \Exception('订单不存在');
        }
        if ($order['freight_status'] === '10' || $order['receipt_status'] === '20') {
            $order->error = '该订单不合法';
            return false;
        }
        //订单返佣
        (new LitestoreorderModel())->add_return_money_bugoods($order->toArray());

        $config = Config::get('site');
        if($config['confirm_receipt_notification'] == 1){
            //邮件通知
            $email = $order['address']['email_address'];
            $msg = 'Your order: '.$order['order_no'].', confirmed receipt！';
            $ret = Emslib::notice($email, $msg);
        }

        return $order->save([
            'receipt_status' => '20',
            'receipt_time' => time(),
            'order_status' => '30'
        ]);
    }

    public function checkGoodsStatusFromOrder($goodsList){
        foreach ($goodsList as $goods) {
            //商品是否下架
            if ($goods['goods']['goods_status'] !== '10') {
                $this->setError('很抱歉，商品 [' . $goods['goods_name'] . '] 已下架');
                return false;
            }
            //付款减库存
            if ($goods['deduct_stock_type'] === '20' && $goods['spec']['stock_num'] < 1) {
                $this->setError('很抱歉，商品 [' . $goods['goods_name'] . '] 库存不足');
                return false;
            }
        }
        return true;
    }

    public function getList($user_id,$request){
        if($request['type'] == 'no_pay'){
            //未付款
            $where['pay_status']=10;
        }elseif($request['type'] == 'no_freight'){
            //未发货
            $where['pay_status']=20;
            $where['freight_status']=10;
        }elseif($request['type'] == 'no_receipt'){
            //未收货
            $where['pay_status']=20;
            $where['freight_status']=20;
            $where['receipt_status']=10;
        }elseif($request['type'] == 'no_pl'){
            //未评论
            $where['order_status']=30;
            $where['is_appraise']=0;
        }else{
            $where=[];
        }
        return $this->with(['goods'])
            ->where('user_id', '=', $user_id)
            ->where('order_status', '<>', '20')
            ->where($where)
            ->order(['createtime' => 'desc'])
            ->paginate(8, false, [ 'page' => $request['page'] ])
            ->each(function($item){
                foreach ($item->goods as $k=>$v){
                    $v['ImageFrist'] = cdnurl(explode(",",$v['images'])[0], true);
                }
            });
    }

    public function getOrderDetail($order_id){
        if (!$order = self::get([
            'order_id' => $order_id,
            'order_status' => ['<>', '20']
        ], ['goods'=>['spec','goods'], 'address'])) {
            throw new \Exception('订单不存在');
        }
        $goodsList = [];
        foreach ($order['goods'] as $index => $item) {
            $item['image'] = cdnurl(explode(",",$item['images'])[0], true);
            $item['sku_image'] = $item['spec']['spec_image']=='' ? '' : cdnurl($item['spec']['spec_image'], true);

            $item['activity_label'] = '';
            if($item['activity_full_id']){
                $item['activity_label'] = Db::name('activity_full')->where('id',$item['activity_full_id'])->value('label');
            }

            $goodsList[] = $item;
        }
        $order['goods'] = $goodsList;
        return $order;
    }

    public function payDetail($order_no){
        return self::get(['order_no' => $order_no, 'pay_status' => 10], ['goods','address']);
    }
    
    public function payDetailById($id){
        return self::get(['order_id' => $id, 'pay_status' => 10], ['goods','address']);
    }

    public function getCart($user_id,$uuid,$request,$address,$order,$code){
        $model = new Cart($user_id,$uuid);
        return $model->getList($request,$address,$order,$code,'order');
    }
    
    public function CarclearAll($user_id,$uuid){
        $Card = new Cart($user_id,$uuid);
        $Card->clearAll();
    }

    public function getBuyNow($user_id,$uuid, $request,$goods_id, $goods_num, $goods_sku_id,$address=[],$code='',$from='')
    {
        // 商品信息
        $goods = Wxlitestoregoods::detail($goods_id);
        $goods['show_error'] = 0;
        // 判断商品是否下架
        if ($goods['goods_status'] !== '10') {
            $goods['show_error'] = 1;
            $goods['show_error_text'] = '已下架';
            $this->setError('Sorry, the product information does not exist or has been removed from the shelf');
//            $this->setError('很抱歉，商品信息不存在或已下架');
        }
        // 商品sku信息
        $goods['goods_sku'] = $goods->getGoodsSku($goods_sku_id);
        // 判断商品库存
        if ($goods_num > $goods['goods_sku']['stock_num']) {
            $goods['show_error'] = 2;
            $goods['show_error_text'] = '库存不足';
            $this->setError('Sorry, the inventory of goods is insufficient');
//            $this->setError('很抱歉，商品库存不足');
        }
        //折扣码如果存在，查询折扣码是否管用
        $rate = 1;//初始化-折扣
        if(!empty($code)){
            //折扣
            $goods_zhekou = \think\Db::name('activity')
                ->where('code',$code)
                ->where('start_time <= '.time())
                ->where('end_time > '.time())
                ->where('status','1')
                ->where('deletetime is null')
                ->where('goods_ids','like',"%".$goods_id."%")->find();
            if(empty($goods_zhekou)){
//                $this->setError('折扣码不存在或已失效');
                $goods['show_error'] = 3;
                $goods['show_error_text'] = 'Discount code does not exist or has expire';
                $this->setError('Discount code does not exist or has expired');
            }else{
                $goods_info = json_decode($goods_zhekou['goods_info'],true);
                $rate = $goods_info[$goods_id];
            }
        }

        // 商品单价
        $goods['rate'] = $rate;//折扣信息
        $goods['goods_price'] = bcmul($goods['goods_sku']['goods_price'], $rate,2);//价格*折扣
        $goods['line_price'] = $goods['goods_sku']['line_price'];
        // 商品总价
        $goods['total_num'] = $goods_num;
        $goods['total_price'] = bcmul($goods['goods_price'], $goods_num, 2);

        /***************满减送赠*******************/
        //折扣、满减送赠都有的情况，只能有一个生效
        $derate_money = 0;//初始化-满减的金额
        $activity_rule = '';//初始化-满减送赠的规则
        $gift_goods = [];//初始化-满送赠的赠品商品信息
        $gift_num = 0;//初始化-满送赠的赠品商品数量
        if(empty($code)){
            $label_full_dec = \think\Db::name('activity_full')
                ->where('start_time <= '.time())
                ->where('end_time > '.time())
                ->where('status','1')
                ->where('deletetime is null')
                ->where('goods_ids','like',"%".$goods_id."%")
                ->find();
            if(!empty($label_full_dec)){
                $dec_rule = json_decode($label_full_dec['rule'],true);
                $dec_rule = array_column($dec_rule,null,'rank');
                array_multisort($dec_rule,SORT_DESC);
                foreach ($dec_rule as $k=>$v){
                    if($label_full_dec['type'] == 1){
                        //满减
                        if($goods['total_price'] >= $v['rank']){
                            $derate_money = $v['reward'];
                            $activity_rule = $label_full_dec['rule'];
                            break;
                        }
                    }elseif($label_full_dec['type'] == 2){
                        //满送（件数）
                        if($goods_num >= $v['rank']){
                            $gift_num = $v['reward'];
                            $goods_spec_id = $label_full_dec['goods_spec_ids_gift'];
                            $activity_rule = $label_full_dec['rule'];

                            //获取赠品商品信息
                            $gift_goods_spec = Db::name('litestore_goods_spec')->where('goods_spec_id',$goods_spec_id)->find();
                            $gift_goods = Wxlitestoregoods::detail($gift_goods_spec['goods_id']);
                            $gift_goods['activity_full_id'] = $label_full_dec['id'];
                            $gift_goods['total_num'] = $gift_num;
                            $gift_goods['total_price'] = '0';
                            $gift_goods['goods_sku'] = $gift_goods->getGoodsSku($gift_goods_spec['spec_sku_id']);
                            $gift_goods['goods_sku']['goods_price'] = '0';
                            unset($gift_goods['category']);
                            unset($gift_goods['spec']);
                            unset($gift_goods['spec_rel']);
                            unset($gift_goods['specRel']);
                            break;
                        }
                    }elseif($label_full_dec['type'] == 3){
                        //满赠（金额）
                        if($goods['total_price'] >= $v['rank']){
                            $gift_num = $v['reward'];
                            $goods_spec_id = $label_full_dec['goods_spec_ids_gift'];
                            $activity_rule = $label_full_dec['rule'];

                            //获取赠品商品信息
                            $gift_goods_spec = Db::name('litestore_goods_spec')->where('goods_spec_id',$goods_spec_id)->find();
                            $gift_goods = Wxlitestoregoods::detail($gift_goods_spec['goods_id']);
                            $gift_goods['activity_full_id'] = $label_full_dec['id'];
                            $gift_goods['total_num'] = $gift_num;
                            $gift_goods['total_price'] = '0';
                            $gift_goods['goods_sku'] = $gift_goods->getGoodsSku($gift_goods_spec['spec_sku_id']);
                            $gift_goods['goods_sku']['goods_price'] = '0';
                            unset($gift_goods['category']);
                            unset($gift_goods['spec']);
                            unset($gift_goods['spec_rel']);
                            unset($gift_goods['specRel']);
                            break;
                        }
                    }
                }
            }
        }
        /***************满减送赠end*******************/

        $totalPrice = $goods['total_price'];
        $totalLinePrice = bcmul($goods['line_price'], $goods_num, 2);
        $goods_list[] = $goods;

        //商品详情中增加赠品商品
        if(empty($code) && $from == 'order'){
            if($gift_goods){
                $goods_list[] = $gift_goods;
            }
        }

        /*************顺手买商品*****************/
        $buy_num = 0;
        //buy_at_will=0,是初进订单确认页面，顺手买商品显示，=1是勾选顺手买商品后重新计算价格，运费，=2是提交订单时没有勾选顺手买，重新赋值为2，此时不需要管顺手买商品
        if(!isset($request['buy_at_will']) || $request['buy_at_will'] == 0){
            $activity_buy = Db::name('activity_buy')
                ->where('start_time <= '.time())
                ->where('end_time > '.time())
                ->where('status','1')
                ->where('deletetime is null')
                ->orderRaw('rand()')
                ->find();//随机一个随手买活动
            if($activity_buy){
                $activity_goods_info = json_decode($activity_buy['goods_info'],true);
                $buy_goods_ids = explode(',',$activity_buy['goods_ids']);
                $buy_key = array_rand($buy_goods_ids,1);//随机一个活动中的商品
                $buy_goods_id = $buy_goods_ids[$buy_key];
                $activity_goods_price = $activity_goods_info[$buy_goods_id];//活动价格

                $buy_goods = Wxlitestoregoods::detail($buy_goods_id);
                //只显示上架的
                if($buy_goods['goods_status'] == 10){
                    $buy_goods_sku_id = Db::name('litestore_goods_spec')
                        ->where('goods_id',$buy_goods_id)
                        ->orderRaw('rand()')
                        ->value('spec_sku_id');//随机商品规格
                    $buy_goods['activity_buy_id'] = $activity_buy['id'];
                    $buy_goods['goods_sku'] = $buy_goods->getGoodsSku($buy_goods_sku_id);
                    //只显示有库存的
                    if($buy_goods['goods_sku']['stock_num'] > 0){
                        $buy_goods['goods_sku']['goods_price'] = $activity_goods_price;
                        unset($buy_goods['category']);
                        unset($buy_goods['spec']);
                        unset($buy_goods['spec_rel']);
                        unset($buy_goods['specRel']);
                    }else{
                        $buy_goods = [];
                    }
                }else{
                    $buy_goods = [];
                }
            }else{
                $buy_goods = [];
            }
        }elseif($request['buy_at_will'] == 1){
            //buy_at_will:1
            //activity_buy_id:1
            //buy_goods_id:25
            //buy_goods_sku_id:60
            $buy_goods_id = $request['buy_goods_id'];
            $buy_goods_sku_id = $request['buy_goods_sku_id'];
            // 商品信息
            $buy_goods = Wxlitestoregoods::detail($buy_goods_id);
            // 商品sku信息
            $buy_goods['goods_sku'] = $buy_goods->getGoodsSku($buy_goods_sku_id);
            // 商品单价
            $activity_buy = Db::name('activity_buy')
                ->where('id',$request['activity_buy_id'])
                ->find();//随手买活动
            $activity_goods_info = json_decode($activity_buy['goods_info'],true);
            $activity_goods_price = $activity_goods_info[$buy_goods_id];//活动价格

            $buy_goods['activity_buy_id'] = $request['activity_buy_id'];//顺手买活动id
            $buy_goods['rate'] = 1;//顺手买无折扣
            $buy_goods['goods_price'] = $buy_goods['goods_sku']['goods_price'] = $activity_goods_price;//商品价格是活动价格
            $buy_goods['line_price'] = $buy_goods['goods_sku']['line_price'];
            // 商品总价
            $buy_num = 1;
            $buy_goods['total_num'] = $buy_num;
            $buy_goods['total_price'] = bcmul($buy_goods['goods_price'], $buy_num, 2);
            $totalPrice += $buy_goods['total_price'];
            $totalLinePrice += bcmul($buy_goods['line_price'], $buy_num, 2);

            // 计算配送费用
            $cart[] = $buy_goods->toArray();

            $goods_list[] = $buy_goods;//商品详情中增加顺手买商品
        }else{
            $buy_goods = [];//立即购买提交订单，顺手买没勾选
        }
        /*************顺手买商品end**************/

        // 计算配送费用
        $cart[] = $goods->toArray();
        $country_code = '';
        $postal_code = '';
        $shipping_type = '';
        $service = '';
        $address_new = [];
        if($user_id){
            $default = Litestoreadress::getdefault($user_id);
//            $default = Db::name('litestore_order_address_en')->where('user_id',$user_id)->order('id desc')->find();
            if($default){
                $country_code = $default['country_code'];
                $postal_code = $default['postal_code'];
                $address_new = $default;
            }
        }
        if($address){
            if(!isset($address['service'])){
                $address['service'] = '';
            }
            $address['country_code'] = $country_code = Db::name('region_city')->where('country',$address['country'])->value('country_code');
            $postal_code = $address['postal_code'];
            $shipping_type = $address['shipping_type'];
            $service = $address['service'];
            $address['state_code'] = Db::name('region_city')->where('country',$address['country'])->where('state',$address['state'])->value('state_code');
            $address_new = $address;
        }
        if($shipping_type == 'Fedex'){
            if(!empty($country_code) && !empty($postal_code) && !empty($service)){
                $get_fedex_freight = (new Fedex())->get_fedex_freight($postal_code,$country_code,$cart,$service);
                if($get_fedex_freight['code'] != 20){
                    $expressPrice = 0.00;
                    $this->setError('Failed to obtain freight,'.$get_fedex_freight['msg']);
                }else{
                    $expressPrice = $get_fedex_freight['freight'];
                }
            }else{
                $expressPrice = 0.00;
//                    $this->setError('地址、邮箱、运送方式不能为空');
                $this->setError('Address, mailbox and shipping method cannot be empty');
            }
        }elseif($shipping_type == 'Usps'){
            if(!empty($country_code) && !empty($postal_code)){
                $get_fedex_freight = (new Usps())->get_usps_freight($postal_code,$country_code,$cart,'RETAIL GROUND');
                if($get_fedex_freight['code'] != 20){
                    $expressPrice = 0.00;
                    $this->setError('Failed to obtain freight,'.$get_fedex_freight['msg']);
                }else{
                    $expressPrice = round($get_fedex_freight['freight'],2);
                }
            }else{
                $expressPrice = 0.00;
//                    $this->setError('地址、邮箱、运送方式不能为空');
                $this->setError('Address, mailbox cannot be empty');
            }
        }else{
            $expressPrice = 0.00;
            //$this->setError('Failed to obtain the shipping method');
        }

        return [
            'goods_list' => $goods_list,               // 商品详情
            'order_total_num' => $goods_num+$gift_num+$buy_num,        // 商品总数量
            'order_total_line_price' => $totalLinePrice,    // 商品划线总金额 (不含运费)
            'order_total_price' => $totalPrice,    // 商品总金额 (不含运费)
            'order_derate_money' => $derate_money,    // 满减-减免的金额
            'express_price' => $expressPrice,    // 配送费用
            'order_pay_price' => round($totalPrice-$derate_money+$expressPrice, 2),  // 实际支付金额
            'address' => $address_new,  // 默认地址；最初进来是上一个订单的地址，修改地址再获取运费是手动填写的地址
            'buy_goods' => $buy_goods,//顺手买商品
            'gift_goods' => $gift_goods,//满送赠奖品（达到条件才有）
            'activity_rule' => $activity_rule,//活动规则
            'has_error' => $this->hasError(),
            'error_msg' => $this->getError(),
        ];
    }

    public function order_add($user_id,$uuid, $order,$blogger_id=0,$code=''){
        // halt(object2array($order));
        Db::startTrans();
        // 记录订单信息
        $order_no = $this->orderNo();
        $this->save([
            'user_id' => $user_id,
            'order_no' => $order_no,
            'total_price' => $order['order_total_price'],
            'order_derate_money' => $order['order_derate_money'],
            'pay_price' => $order['order_pay_price'],
            'express_price' => $order['express_price'],
            'parent_user_id' => $blogger_id,
            'code' => $code,
            'activity_rule' => $order['activity_rule'],
        ]);
        // 订单商品列表
        $goodsList = [];
        // 更新商品库存 (下单减库存)
        $deductStockData = [];
        foreach ($order['goods_list'] as $goods) {
            $activity_buy_id = 0;
            if(isset($goods['activity_buy_id'])){
                $activity_buy_id = $goods['activity_buy_id'];
            }
            $activity_full_id = 0;
            if(isset($goods['activity_full_id'])){
                $activity_full_id = $goods['activity_full_id'];
            }
            $blogger_rate = 0;
            if($blogger_id){
                if(!isset($goods['activity_buy_id']) && !isset($goods['activity_full_id'])){
                    $blogger_rate = Db::name('user_goods')->where('user_id',$blogger_id)->where('goods_id',$goods['goods_id'])->where('deletetime is null')->value('blogger_rate');
                }
            }
            /* @var Goods $goods */
            $goodsList[] = [
                'user_id' => $user_id,
                'goods_id' => $goods['goods_id'],
                'goods_name' => $goods['goods_name'],
                'images' => $goods['images'],
                'deduct_stock_type' => $goods['deduct_stock_type'],
                'spec_type' => $goods['spec_type'],
                'spec_sku_id' => $goods['goods_sku']['spec_sku_id'],
                'goods_spec_id' => $goods['goods_sku']['goods_spec_id'],
                'goods_attr' => $goods['goods_sku']['goods_attr'],
                'content' => $goods['content'],
                'goods_no' => $goods['goods_sku']['goods_no'],
                'goods_price' => $goods['goods_sku']['goods_price'],
                'line_price' => $goods['goods_sku']['line_price'],
                'cost_price' => $goods['goods_sku']['cost_price'],
                'goods_weight' => $goods['goods_sku']['goods_weight'],
                'total_num' => $goods['total_num'],
                'total_price' => $goods['total_price'],
                'blogger_rate' => $blogger_rate,
                'activity_discount_rate' => isset($goods['rate']) ? $goods['rate'] : 1,
                'activity_buy_id' => $activity_buy_id,
                'activity_full_id' => $activity_full_id,
            ];
            // 下单减库存
            $goods['deduct_stock_type'] === '10' && $deductStockData[] = [
                'goods_spec_id' => $goods['goods_sku']['goods_spec_id'],
                'stock_num' => ['dec', $goods['total_num']]
            ];
        }
        // 保存订单商品信息
        $this->goods()->saveAll($goodsList);
        // 更新商品库存
        !empty($deductStockData) && (new Litestoregoodsspec)->isUpdate()->saveAll($deductStockData);
        // 记录收货地址
        $this->address()->save([
            'user_id' => $user_id,
            'first_name' => $order['address']['first_name'],
            'last_name' => $order['address']['last_name'],
            'email_address' => $order['address']['email_address'],
            'phone_number' => $order['address']['phone_number'],
            'country' => $order['address']['country'],
            'country_code' => $order['address']['country_code'],
            'state' => $order['address']['state'],
            'state_code' => $order['address']['state_code'],
            'city' => $order['address']['city'],
            'detail' => $order['address']['detail'],
            'postal_code' => $order['address']['postal_code'],
            'service' => $order['address']['service'],
        ]);

        $config = Config::get('site');
        if($config['order_notification'] == 1){
            //下单邮件通知
            $email = $order['address']['email_address'];
            $msg = 'Your order: '.$order_no.', has been placed successfully';
            $ret = Emslib::notice($email, $msg);
        }

        Db::commit();
        return true;
    }
    
    public function getPayStatusList()
    {
        return ['10' => __('Unpaid'),'20' => __('Paid')];
    }     

    public function getFreightStatusList()
    {
        return ['10' => __('To be shipped'),'20' => __('Shipped')];
    }     

    public function getReceiptStatusList()
    {
        return ['10' => __('Goods not received'),'20' => __('Goods received')];
    }     

    public function getOrderStatusList()
    {
        return ['10' => __('In progress'),'20' => __('Cancel'),'30' => __('Completed')];
    }     


    public function getPayStatusTextAttr($value, $data)
    {        
        $value = $value ? $value : (isset($data['pay_status']) ? $data['pay_status'] : '');
        $list = $this->getPayStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_time']) ? $data['pay_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getFreightStatusTextAttr($value, $data)
    {        
        $value = $value ? $value : (isset($data['freight_status']) ? $data['freight_status'] : '');
        $list = $this->getFreightStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getFreightTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['freight_time']) ? $data['freight_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getReceiptStatusTextAttr($value, $data)
    {        
        $value = $value ? $value : (isset($data['receipt_status']) ? $data['receipt_status'] : '');
        $list = $this->getReceiptStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getReceiptTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['receipt_time']) ? $data['receipt_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getOrderStatusTextAttr($value, $data)
    {        
        $value = $value ? $value : (isset($data['order_status']) ? $data['order_status'] : '');
        $list = $this->getOrderStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getCreattimeTextAttr($value, $data)
    {        
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;;
    }

    protected function setPayTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setFreightTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setReceiptTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    public function goods()
    {
        return $this->hasMany('Litestoreordergoods','order_id', 'id');
    }

    public function address()
    {
        return $this->hasOne('Litestoreorderaddressen', 'order_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    private function setError($error)
    {
        empty($this->error) && $this->error = $error;
    }

    protected function orderNo()
    {
        return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

    public function hasError()
    {
        return !empty($this->error);
    }

    //更新商品库存、销量,订单状态
    public function updatePayStatus($transaction_id,$pay_type='')
    {
        Db::startTrans();
        // 更新商品库存、销量
        $GoodsModel = new Wxlitestoregoods;
        $GoodsModel->updateStockSales($this['goods']);
        // 更新订单状态
        $this->save([
            'pay_status' => '20',
            'pay_time' => time(),
            'pay_type' => $pay_type,
            'transaction_id' => $transaction_id,
        ]);

        //邮件通知
        $email = $this['address']['email_address'];
        $ret = Emslib::order_notice($email, $this,'pay');

        Db::commit();
        return true;
    }

    public function order_receipt_timing($days){
        $t = time() - $days * 86400;
        $order = self::all([
            'freight_status' => 20,
            'receipt_status' => 10,
            'order_status' => 10,
            'freight_time'=>['<',$t]
        ],['goods']);
        if (!$order) {
            return false;
        }
//        halt(object2array($order));
        foreach($order as $k=>$v){
            //订单返佣
            (new LitestoreorderModel())->add_return_money_bugoods($v->toArray());

            $v->save([
                'receipt_status' => '20',
                'receipt_time' => time(),
                'order_status' => '30'
            ]);
        }
        return true;
    }
}
